/* Copyright (c) 2013 fab-o-lab

 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation
 files (the "Software"), to deal in the Software without
 restriction, including without limitation the rights to use,
 copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the
 Software is furnished to do so, subject to the following
 conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 OTHER DEALINGS IN THE SOFTWARE.
*/

package com.fabolab.jetset.core;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import com.fabolab.jetset.core.config.model.Context;
import com.fabolab.jetset.core.servlet.http.HttpServletRequest;


public class WikiUtils {
	
	public String parseMenu(String menuText) {
		// with |
		menuText = menuText.replaceAll("\\[\\[([^\\]\\]]*?)\\|(.*?)\\]\\]",
				"<li><a href=\"$2\">$1</a></li>"); 
		// without |
		menuText = menuText.replaceAll("\\[\\[([^\\|]*?)\\]\\]",
				"<li><a href=\"$1\">$1</a></li>");
		menuText = menuText.replaceAll("\n", "");
		return menuText;
	}

	public String parseWiki(String text) {
		// table start

		text = text.replaceAll("(^|\\n)\\{\\|([^\\n]*)",
				"$1<table class=\"text_area\" $2><tr>");
		//        
		// // table end
		text = text.replaceAll("(^|\\n)\\|\\}", "$1<\\/tr><\\/table>");
		//        
		// // table caption
		text = text.replaceAll("(^|\\n)\\|\\+([^\\n]*)",
				"<caption>$2<\\/caption>");
		//        
		// // table new row
		text = text.replaceAll("(^|\\n)\\|\\-", "<\\/tr><tr>");
		//        
		// // table data
		text = text.replaceAll("(^|\\n)\\|\\s([^\\n]*)",
				"(^|\\n)\\|\\s([^\\n]*)");

		// text = text.replace(/(^|\n)\|\s([^\n]*)/g, function(str, $1, $2)
		// {
		// $2 = $2.replace(/(\|\|)/g, "<\/td><td>");
		// return "<td>" + $2 + "<\/td>";
		// });
		//
		//image
		text = text.replaceAll("\\[\\[\\[!([^\\]\\]]*?)\\|(.*?)\\]\\]\\]",
				"<span><img src=\"files/$2\"><br>$1<\\span>");
		// image without |
		text = text.replaceAll("\\[\\[\\[!([^\\|]*?)\\]\\]\\]",
				"<img src=\"files/$1\">");
		// document link 
		text = text.replaceAll("\\[\\[\\[([^\\]\\]]*?)\\|(.*?)\\]\\]\\]",
				"<a class=\"document\" href=\"files/$2\" target=\"_new\">$1<\\/a>");		
		// document without |
		text = text.replaceAll("\\[\\[\\[([^\\|]*?)\\]\\]\\]",
				"<a class=\"document\" href=\"files/$1\" target=\"_new\">$1<\\/a>");		
		// // Backup link
		// with |
		text = text.replaceAll("\\[\\[backup,([^\\]\\]]*?)\\|(.*?)\\]\\]",
				"<a class=\"backup\" href=\"?cmd=backup&source=$1&file=$2\">$2<\\/a>");		
		// // links
		// with |
		text = text.replaceAll("\\[\\[([^\\]\\]]*?)\\|(.*?)\\]\\]",
				"<a class=\"world\" href=\"$2\">$1<\\/a>"); // "<a
																				// class=\"wiki\"
																				// onclick='go_to(\"$2\")'>$1<\/a>");
		// without |
		text = text.replaceAll("\\[\\[([^\\|]*?)\\]\\]",
				"<a class=\"world\" href=\"$1\">$1<\\/a>");
		// {
		// if($1.match("://"))
		// return "<a class=\"world\" href=\"" + $1 + "\" target=\"_blank\">" +
		// $1 + "<\/a>";
		// if(page_exists($1))
		// return "<a class=\"link\" onclick='go_to(\"" + valid_name($1)
		// +"\")'>" + $1 + "<\/a>";
		// else
		// return "<a class=\"unlink\" onclick='go_to(\"" + valid_name($1)
		// +"\")'>" + $1 + "<\/a>";
		// }); //"<a class=\"wiki\" onclick='go_to(\"$1\")'>$1<\/a>");
		// lists
		text = text.replaceAll("(^|\\n)\\+\\s([^\\n\\+]*)",
				"$1<ul><li>$2<\\/li><\\/ul>");
		text = text.replaceAll("(^|\\n)\\+\\+\\s([^\\n\\+]*)",
				"$1<ul><ul><li>$2<\\/li><\\/ul><\\/ul>");
		text = text.replaceAll("(^|\\n)\\+\\+\\+\\s([^\\n\\+]*)",
				"$1<ul><ul><ul><li>$2<\\/li><\\/ul><\\/ul><\\/ul>");
		text = text.replaceAll("(^|\\n)\\+\\+\\+\\+\\s([^\\n\\+]*)",
				"$1<ul><ul><ul><ul><li>$2<\\/li><\\/ul><\\/ul><\\/ul><\\/ul>");
		for (int i = 0; i < 4; i++) {
			text = text.replaceAll("\\<\\/ul\\>\\<ul\\>", "");
			text = text.replaceAll("\\<\\/ul\\>\\n\\<ul\\>", "");
		}
		// numbererd lists
		text = text.replaceAll("(^|\\n)#\\s([^\\n\\+]*)",
				"$1<ol><li>$2<\\/li><\\/ol>");
		text = text.replaceAll("(^|\\n)##\\s([^\\n\\+]*)",
				"$1<ol><ol><li>$2<\\/li><\\/ol><\\/ol>");
		text = text.replaceAll("(^|\\n)###\\s([^\\n\\+]*)",
				"$1<ol><ol><ol><li>$2<\\/li><\\/ol><\\/ol><\\/ol>");
		text = text.replaceAll("(^|\\n)####\\s([^\\n\\+]*)",
				"$1<ol><ol><ol><ol><li>$2<\\/li><\\/ol><\\/ol><\\/ol><\\/ol>");
		for (int i = 0; i < 4; i++) {
			text = text.replaceAll("\\<\\/ol\\>\\<ol\\>", "");
			text = text.replaceAll("\\<\\/ol\\>\\n\\<ol\\>", "");
		}
		// headers
		text = text.replaceAll("(^|\\n)!([^!].*)", "<h2>$2<\\/h2>");
		text = text.replaceAll("(^|\\n)!!([^!].*)", "<h3>$2<\\/h3>");
		text = text.replaceAll("(^|\\n)!!!(.*)", "<h4>$2<\\/h4>");
		// <b>
		text = text.replaceAll("(^|\\n|\\s|\\>|\\/)\\*(.*?)\\*",
				"$1<b>$2<\\/b>");
		// <i>
		text = text.replaceAll("(^|\\n|\\s|\\>|\\*)\\/(.*?)\\/",
				"$1<i>$2<\\/i>");
		// <u>
		text = text.replaceAll("(^|\\n|\\s|\\>|\\*)_(.*?)_", "$1<u>$2<\\/u>");
		// <hr>
		text = text.replaceAll("(^|\\n)\\-\\-\\-(\\n|$)", "<hr>");
		// <strike>
		// text = text.replace(/(^|\n|\s|\>|\*)\-(.*?)\-/g,
		// "$1<strike>$2<\/strike>");
		// <br>
		text = text.replaceAll("\\n\\n", "</p><p>");
		// text = "<p>" + text + "</p>";
		text = text.replaceAll("(\\<\\/h.\\>)\\n", "$1");
		text = text.replaceAll("(\\<\\/ul\\>)\\n", "$1");
		text = text.replaceAll("(\\<\\/ol\\>)\\n", "$1");
		text = text.replaceAll("(\\<\\/li\\>)\\n", "$1");
		text = text.replaceAll("\\n", "<br>");
		// if(ie == true)
		// {
		// text = escape(text);
		// text = text.replace("%OD%OA", "<br>");
		// text = unescape(text);
		// }
		
		// Form processing
		// TODO use a hash table to lookup actions
		text = text.replaceAll("�form([^\\]\\]]*?)\\|(.*?)�",
		"<form method=\"post\"><input type=\"hidden\" name=\"cmd\" value=\"saveform\">");	
		text = text.replaceAll("�text\\|(.*?)\\|(.*?)�",
		"<span class=\"field\">$1</span>:&nbsp;<input type=\"text\" name=\"field-$1\" id=\"$1\" size=\"$2\">");
		text = text.replaceAll("�end-form�",
		"</form><input type=\"submit\" value=\"OK\">");	
		

		return text;
	}

	public String getLink(String $1, String $2) {
		if ($2.matches("://"))
			return "<a class=\"world\" href=\"" + $2 + "\" target=\"_blank\">"
					+ $1 + "<\\a>";
		if (pageExists($2))
			return "<a class=\"link\" onclick='go_to(\"" + validName($2)
					+ "\")'>" + $1 + "<\\a>";
		else
			return "<a class=\"unlink\" onclick='go_to(\"" + validName($2)
					+ "\")'>" + $1 + "<\\a>";
	}

	public boolean pageExists(String file) {
		return (true);
	}

	public String validName(String file) {
		return (file);
	}

	public String getTemplate(String fileName) {
		// TODO load file
		String text = "";
		File file = new File(fileName);
		//log("getting " + file.getPath());
		BufferedReader reader;
		try {
			reader = new BufferedReader(new FileReader(file));

			String line;

			while ((line = reader.readLine()) != null) {
				text += line + "\n";
			}

			reader.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			text = "Error finding template.";
		} catch (IOException e) {
			// TODO Auto-generated catch block
			text = "Error reading template";
		}

		return (text);
	}
	
	public String composePage(Context context, String template,String wiki, String menu) {
		// TODO replace template body and menu in template
		String result = "";
		result = template.replaceFirst("�fhs.body�", wiki);
		result = result.replaceFirst("�fhs.menu�", menu);
		result = result.replaceFirst("�fhs.header1�", context.getResources()
				.getString("fhs.header1"));
		result = result.replaceFirst("�fhs.header2�", context.getPageTitle());
		result = result.replaceFirst("�fhs.title�", context.getPageTitle());		
		result = result.replaceFirst("�fhs.edit�", context.getResources()
				.getString("fhs.edit"));		
		result = result.replaceFirst("�fhs.imageupload�", context.getResources()
						.getString("fhs.imageupload"));
		result = result.replaceFirst("�fhs.editmenu�", context.getResources()
				.getString("fhs.editmenu"));
		result = result.replaceFirst("�fhs.edit.url�", context.getPath()
				+ "?cmd=edit");
		result = result.replaceFirst("�fhs.editmenu.url�", context.getPath()
				+ "?cmd=editmenu");
		result = result.replaceFirst("�fhs.imageupload.url�", context.getPath()
				+ "?cmd=askimage");		
		result = result.replaceFirst("�fhs.prefs�", context.getResources()
				.getString("fhs.prefs"));
		result = result.replaceFirst("�fhs.copyright�", context.getResources()
				.getString("fhs.copyright"));

		return (result);
	}
	
	
}
